package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Grading;
import com.sl.au.entity.Option;
import com.sl.au.service.GradingService;
import com.sl.au.service.GridUserDetailsService;
import com.sl.au.service.OptionService;
import com.sl.au.service.TemplateDetailsService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

/**
 * 评分等级管理
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/grading")
public class GradingController extends BaseController {

	@Autowired
	GradingService gradingService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	TemplateDetailsService templateDetailsService;
	
	@Autowired
	GridUserDetailsService gridUserDetailsService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView modelAndView = this.createLayoutView("grading/gradingindex");
		List<Option> options = optionService.getRepository().findByGroup("评分层级");
		modelAndView.addObject("options", options);
		return modelAndView;
	}
	
	/**
	 * 显示区域结构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BussinessLevel> node=null;
		List<Grading> node = null;
		
		//node=bussinessLevelService.getAllNodes();
		node = gradingService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=gradingService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
	
	/**
	 * 获取节点信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getNode",method = RequestMethod.GET)
	public Map<String,Object> getNode(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String Id=request.getParameter("Id");
		Grading node = gradingService.getRepository().findOne(Id);
		int useNum = templateDetailsService.getRepository().getGradingNum(Id) + gridUserDetailsService.getRepository().getGradingNum(Id);
		map.put("node", node);
		map.put("useNum", useNum);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<Grading> modules=null;
		long count = 0;
		
		modules = gradingService.getGradingByKey(start, length, key, null, null);
		count=gradingService.getGradingByKeyCount(key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getchildrenpage", method = RequestMethod.POST)
	public Map<String,Object> getchildrenpage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String id=request.getParameter("id");
		List<Grading> modules=null;
		long count = 0;
		
		modules = gradingService.getChildrenGradingByKey(start, length, id, key, null, null);
		count=gradingService.getChildrenGradingByKeyCount(id, key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存/修改信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public MsgHelper saveGrading(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = null;
		String id = (String) map.get("id");
		String gradingName = (String) map.get("gradingName");
		String gradingIdentify = (String) map.get("gradingIdentify");
		String gradingLevelId = (String) map.get("gradingLevel");
		String gradingBewrite = (String) map.get("gradingBewrite");
		Option gradingLevel = optionService.getRepository().findOne(gradingLevelId);
		
		String sGradingScale = (String) map.get("gradingScale");
		float gradingScale = ExdeUtil.str2float(sGradingScale);
		
		boolean userShow = ExdeUtil.str2boolean(map.get("userShow"));
		boolean partShow = ExdeUtil.str2boolean( map.get("partShow"));
		boolean gridShow = ExdeUtil.str2boolean( map.get("gridShow"));
		boolean eventShow = ExdeUtil.str2boolean( map.get("eventShow"));
		
		Grading grading = null;
		Grading sameGrading = null;
		if(!id.equals("")){
			grading = gradingService.getRepository().findOne(id);
			sameGrading = gradingService.getRepository().findTopByGradingParentAndGradingIdentify(grading.getGradingParent(), gradingIdentify);
			if(grading.getGradingParent() == null || sameGrading == null || sameGrading.getId().equals(id)) {
				grading.setUpdateTime(new Date());
				grading.setGradingBewrite(gradingBewrite);
				grading.setGradingName(gradingName);
				grading.setGradingIdentify(gradingIdentify);
				grading.setGradingLevel(gradingLevel);
				
				grading.setUserShow(userShow);
				grading.setPartShow(partShow);
				grading.setGridShow(gridShow);
				grading.setEventShow(eventShow);
				
				grading.setGradingScale(gradingScale);
				
				gradingService.getRepository().save(grading);
				msgHelper = MsgHelper.success();
				msgHelper.setMsg("评分层级修改成功!");
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同部件编码,不能进行修改!");
			}
		}else{
			grading = new Grading();
			grading.setGradingBewrite(gradingBewrite);
			grading.setGradingName(gradingName);
			grading.setGradingIdentify(gradingIdentify);
			grading.setGradingLevel(gradingLevel);
			
			grading.setUserShow(userShow);
			grading.setPartShow(partShow);
			grading.setGridShow(gridShow);
			grading.setEventShow(eventShow);
			
			grading.setGradingScale(gradingScale);
			
			gradingService.getRepository().save(grading);
			msgHelper = MsgHelper.success();
			msgHelper.setMsg("评分层级新增成功!");
		}
		
		return msgHelper;
	};
	
	/**
	 * 删除信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public MsgHelper deleteGrading(@PathVariable("id") String id) {
		MsgHelper msgHelper = null;
		int useNum = templateDetailsService.getRepository().getGradingNum(id) + gridUserDetailsService.getRepository().getGradingNum(id);
		if(useNum == 0) {
			msgHelper = MsgHelper.success();
			msgHelper.setMsg("删除成功!");
			gradingService.getRepository().delete(id);
		}else {
			msgHelper = MsgHelper.failed();
			msgHelper.setMsg("此层级已被使用，不能删除!");
		}
		
		return msgHelper;
	}
	
	/**
	 * 绑定层级关系
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/saveNode",method = RequestMethod.POST)
	public Map<String,Object> saveNode(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		String id = (String) map.get("id");
		String parentId = String.valueOf(map.get("parentId"));
		Grading grading = gradingService.getRepository().findOne(id);
		Grading sameGrading = gradingService.getRepository().findTopByGradingParent(parentId);
		if(sameGrading == null) {
			int gradingOrder = gradingService.getRepository().getGradingOrder(parentId);
			grading.setGradingOrder(gradingOrder);
			grading.setGradingParent(parentId);
			gradingService.getRepository().save(grading);
			msg.put("code", 1);
			msg.put("Grading", grading);
		}else {
			msg.put("code", 0);
			msg.put("msg", "此层级内已存在评分层级,不能进行绑定!");
		}
		return msg;
	};
	
	/**
	 * 移除节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/deleteNodes")
	public Map deleteNode(@RequestBody Map<String,Object> map)
	{
		String str=String.valueOf(map.get("str"));
		//暂未使用
		//String selectPId= String.valueOf(map.get("selectPId"));
		String ids[]=str.split(",");
		//删除用户信息，暂未处理
		//businesssellerBaseInfoService.deleteBussinessLevel(ids);
		gradingService.deleteNodes(ids);
		map.put("code", 1);
		return map;
	}
	
	/**
	 * 移除节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/move")
	public Map moveNode(@RequestBody Map<String,Object> map)
	{
		String id=String.valueOf(map.get("id"));
		String targetId = String.valueOf(map.get("targetId"));
		String moveType = String.valueOf(map.get("moveType"));
		Grading targetNode = gradingService.getRepository().findOne(targetId);
		Grading node = gradingService.getRepository().findOne(id);
		String nodeGradingParent = node.getGradingParent();
		String gradingParent = null;
		Grading sameGrading = null;
		int gradingOrder = 0;
		if("inner".equals(moveType)) {
			gradingParent = targetNode.getId();
			sameGrading = gradingService.getRepository().findTopByGradingParentAndGradingIdentify(gradingParent, node.getGradingIdentify());
			if(sameGrading == null) {
				node.setGradingParent(gradingParent);
				node.setGradingOrder(gradingOrder);
				gradingService.getRepository().save(node);
			}
		}else {
			gradingParent = targetNode.getGradingParent();
			sameGrading = gradingService.getRepository().findTopByGradingParentAndGradingIdentify(gradingParent, node.getGradingIdentify());
			if(sameGrading == null) {
				gradingOrder = targetNode.getGradingOrder();
				if("next".equals(moveType)) {
					gradingOrder = gradingOrder + 1;
				}else {
					gradingOrder = gradingOrder - 1;
				}
				node.setGradingParent(gradingParent);
				node.setGradingOrder(gradingOrder);
				gradingService.getRepository().save(node);
			}
		}
		if(sameGrading == null) {
			//拉动之后进行重新排序
			gradingService.setGradingOrder(gradingParent);
			//原始数据进行排序
			gradingService.setGradingOrder(nodeGradingParent);
			map.put("code", 1);
		}else {
			map.put("code", 0);
			map.put("msg", "此层级已存在相同评分编码,不能进行绑定!");
		}
		return map;
	}
}
